<?php
/**
 * Created by PhpStorm.
 * User: wb-liuyuguang
 * Date: 14-5-19
 * Time: 上午10:34
 */

class GitWebsite{
    private $session;
    public function __construct(){
        $session = false;
    }

    public function login($url, $usr, $pwd){
        $ch = curl_init($url); //初始化
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, 1); //返回header部分
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //返回字符串，而非直接输出
        curl_setopt($ch, CURLOPT_POST, 1);
        $form = array('user[login]'=>urlencode($usr),
            'user[password]'=>$pwd);
        $items = array();
        foreach($form as $key=>$val){
            array_push($items, $key.'='.$val);
        }
        $parameters = join('&', $items);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters );
        $content = curl_exec($ch);
        // 关闭CURL
        if( $content === false ){
            curl_close($ch);
            return;
        }
        curl_close($ch);

        // 解析HTTP数据流
        list($header, $body) = explode("\r\n\r\n", $content);
        // 解析COOKIE
        preg_match("/set\-cookie:([^\r\n]*)/i", $header, $matches);
        // 后面用CURL提交的时候可以直接使用
        // curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        $cookie = $matches[1];
        $this->session = $cookie;
    }

    public function get($url){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_COOKIE, $this->session);
        //curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file); //使用上面获取的cookies
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }

    public function deploy($url, $local, $zip=false){
        $content = $this->get($url);
        if( $content === false){
            return false;
        }
        $dest = $local;
        if( $zip === true ){
            $dest = dirname(__FILE__).'/temp.zip';
        }
        if( false === file_put_contents($dest, $content) ){
            return false;
        }

        if( $zip === true ){
            $zip = new ZipArchive;//新建一个ZipArchive的对象
            if ($zip->open($dest) === true){
                $zip->extractTo($local);
                $zip->close();//关闭处理的zip文件
            }
        }
        return true;
    }
}